<template>
	<view class="chat-container">
		<view class="navigation">

			<view class="status" :style="{ height: getStatusBarHeight() }"></view>

			<view class="header-buttons" :style="{ height: getNavigationBarHeight() }">
				<view class="back-btn" @click="handleBack">
					<uni-icons type="back" size="24"></uni-icons>
				</view>

				<view class="history-btn" @click="toggleHistory">
					<uni-icons type="list" size="24"></uni-icons>
					<text class="history-text">对话记录</text>
				</view>
			</view>
		</view>

		<!-- 侧边栏 -->
		<view class="sidebar" :class="{ 'sidebar-show': showHistory }">
			<view class="sidebar-header">
				<text class="sidebar-title">历史记录</text>
				<text class="close-btn" @tap="toggleHistory">×</text>
			</view>

			<scroll-view class="history-list" scroll-y>
				<view v-for="(record, index) in historyRecords" :key="index" class="history-item">
					<view class="history-item-content" @click="selectSession(record.sessionId)">
						<text class="question-text">{{ record.lastQuestion }}</text>
						<text class="time-text">{{ dateTimeFormat(record.updateTime) }}</text>
					</view>
					<view class="delete-btn" @click.stop="deleteSession(record.sessionId)"
						style="border: 1px red dashed;">
						<uni-icons type="trash" size="20" color="#ff0004"></uni-icons>
					</view>
				</view>
			</scroll-view>

			<view class="new-chat-btn" @click="createNewSession">
				<text>新建对话</text>
			</view>
		</view>

		<!-- 聊天内容区域 -->
		<scroll-view ref="scrollView" class="chat-content" scroll-y scroll-with-animation :scroll-top="scrollTop">
			<view class="message-list">
				<!-- 默认欢迎消息 -->
				<view class="message ai-message">
					<view class="avatar">
						<image src="/static/laozhongyi.png" mode="aspectFill"></image>
					</view>
					<view class="message-content">
						<text>你好！老夫行医数十载，见过不少病人。今日得与你交流，甚是欣慰。请你详细描述一下你的身体状况，老夫可给与你调理养生之法。</text>
					</view>
				</view>

				<!-- 动态消息列表 -->
				<view v-for="(item, index) in messages" :key="index"
					:class="['message', item.type === 'user' ? 'user-message' : 'ai-message']">
					<view class="avatar">
						<image v-if="item.type === 'user'" :src="avatar" mode="aspectFill"></image>
						<image v-else src="/static/laozhongyi.png" mode="aspectFill"></image>
					</view>
					<view class="message-content" v-if="item.type === 'user'">
						<text>{{ item.content }}</text>
					</view>
					<view class="message-content" v-else>
						<view v-if="isLoading && index === messages.length - 1">
							<view class="circle-container">
								<text class="circle"></text>
								<text class="circle"></text>
								<text class="circle"></text>
							</view>
						</view>
						<template v-else>
							<!-- <towxml :nodes="appContext.$towxml(item.content, 'markdown')"></towxml> -->
							<zero-markdown-view :markdown="item.content"></zero-markdown-view>
						</template>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部输入区域 -->
		<view class="chat-footer">
			<view class="input-wrapper">
				<input type="text" class="chat-input" placeholder="请输入您的问题..." v-model="userInput"
					@confirm="sendMessage" />
				<button class="send-button" @click="sendMessage">发送</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	getCurrentInstance,
	nextTick
} from 'vue'
import request from '@/utils/request.js'
import { dateTimeFormat } from '@/utils/system'
import {
	getStatusBarHeight,
	getNavigationBarHeight
} from '@/utils/component-api.js'

const instance = getCurrentInstance()
const appContext = ref(null)
appContext.value = instance.appContext.config.globalProperties
const messages = ref([])
const userInput = ref('')
const currentSessionId = ref('')
const showHistory = ref(false)
const historyRecords = ref([])
const scrollView = ref(null)
const scrollTop = ref(0)
const userInfo = uni.getStorageSync('userInfo')
const avatar = userInfo.avatar
const isLoading = ref(false)

const handleBack = () => {
	uni.navigateBack({
		delta: 1
	});
}

const scrollToBottom = () => {
	// 获取消息列表的高度
	const query = uni.createSelectorQuery()
	query.select('.message-list').boundingClientRect(data => {
		if (data) {
			scrollTop.value = data.height + 1000
		}
	}).exec()
}

const sendMessage = () => {
	if (!userInput.value.trim()) return

	// 添加用户消息
	messages.value.push({
		type: 'user',
		content: userInput.value
	})

	// 滚动到底部
	nextTick(() => {
		scrollToBottom()
	})

	const userMessage = userInput.value

	// 创建新的AI消息对象
	const aiMessage = {
		type: 'ai',
		content: ref('')
	}
	messages.value.push(aiMessage)

	// 开始获取AI响应
	startStream(aiMessage, userMessage)

	// 清空输入
	userInput.value = ''
}

// 开始流式请求
const startStream = async (aiMessage, userMessage) => {
	try {
		isLoading.value = true // 开始加载
		
		const res = await request.post('/chat', {
			content: userMessage,
			userId: uni.getStorageSync("userInfo").id,
			sessionId: currentSessionId.value
		})
		
		isLoading.value = false // 结束加载
		aiMessage.content.value = res.data.answer
		if (!currentSessionId.value) {
			currentSessionId.value = res.data.sessionId
		}

		nextTick(() => {
			scrollToBottom()
		})
	} catch (error) {
		isLoading.value = false // 发生错误时也要结束加载
		aiMessage.content.value = '抱歉，发生了一些错误，请稍后重试。'
		uni.showToast({
			title: error.message || '请求失败',
			icon: 'none'
		})
	}
}

// 切换侧边栏显示
const toggleHistory = () => {
	showHistory.value = !showHistory.value
	if (showHistory.value) {
		fetchHistoryRecords()
	}
}

// 获取历史记录
const fetchHistoryRecords = async () => {
	try {
		const res = await request.get('/chat/history', {
			userId: uni.getStorageSync("userInfo").id
		})
		console.log(res.data)
		historyRecords.value = res.data
	} catch (error) {
		uni.showToast({
			title: error || '获取历史记录失败',
			icon: 'none'
		})
	}
}

// 选择会话
const selectSession = (sessionId) => {
	currentSessionId.value = sessionId
	showHistory.value = false
	// 加载选中会话的聊天记录
	loadSessionMessages(sessionId)
}

// 创建新会话
const createNewSession = () => {
	currentSessionId.value = ''
	messages.value = []
	showHistory.value = false
}

// 加载会话消息
const loadSessionMessages = async (sessionId) => {
	try {
		const res = await request.get('/chat/messages', {
			sessionId
		})
		messages.value = JSON.parse(res.data)
		console.log(messages.value)

		// 加载完历史消息后滚动到底部
		nextTick(() => {
			scrollToBottom()
		})
	} catch (error) {
		uni.showToast({
			title: error || '加载会话消息失败',
			icon: 'none'
		})
	}
}

// 删除会话
const deleteSession = async (sessionId) => {
	// 显示确认弹窗
	const res = await uni.showModal({
		title: '提示',
		content: '确定要删除这条对话记录吗？',
		confirmText: '删除',
		confirmColor: '#ff0000'
	});

	if (!res.confirm) {
		return;
	} else {
		try {
			const result = await request.get('/chat/delete', {
				sessionId
			});

			// 从列表中移除被删除的会话
			historyRecords.value = historyRecords.value.filter(
				record => record.sessionId !== sessionId
			);

			// 如果当前正在查看的是被删除的会话，则创建新会话
			if (currentSessionId.value === sessionId) {
				createNewSession();
			}
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			});
		} catch (error) {
			uni.showToast({
				title: error || '删除失败',
				icon: 'error'
			});
		}
	}
}
</script>

<style scoped>
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

.chat-header {
	padding: 20rpx;
	background-color: #007AFF;
	color: white;
	text-align: center;
}

.header-title {
	font-size: 36rpx;
	font-weight: bold;
}

.chat-content {
	flex: 1;
	padding: 20rpx;
	overflow-y: auto;
}

.message-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.message {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: #007AFF;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	overflow: hidden;
}

.avatar image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

.user-message {
	margin-right: 40rpx;
	flex-direction: row-reverse;
}

.user-message .avatar {
	background-color: #91d5ff;
}

.user-message .message-content {
	background-color: #007AFF;
	color: white;
}

.ai-message .message-content {
	background-color: white;
}

.message-content {
	max-width: 70%;
	padding: 20rpx;
	border-radius: 20rpx;
	font-size: 28rpx;
	line-height: 1.5;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.chat-footer {
	padding: 20rpx;
	background-color: white;
	border-top: 2rpx solid #eee;
}

.input-wrapper {
	display: flex;
	gap: 20rpx;
}

.chat-input {
	flex: 1;
	height: 80rpx;
	padding: 0 20rpx;
	border-radius: 40rpx;
	background-color: #f5f5f5;
	font-size: 28rpx;
}

.send-button {
	width: 160rpx;
	height: 80rpx;
	line-height: 80rpx;
	background-color: #007AFF;
	color: white;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.navigation {
	background-color: #fff;
}

.header-buttons {
	display: flex;
	justify-content: flex-start;
	padding-left: 6rpx;
}

.back-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 25rpx;
}

.history-btn {
	background: none;
	border: none;
	text-align: left;
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.history-text {
	color: #333;
	font-size: 28rpx;
	font-weight: 500;
	margin-left: 6rpx;
}

.sidebar {
	margin-top: 150rpx;
	position: fixed;
	top: 0;
	left: -80%;
	width: 80%;
	height: calc(100% - 160rpx);
	background-color: #fff;
	box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
	z-index: 1000;
}

.sidebar-show {
	left: 0;
}

.sidebar-header {
	padding: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid #eee;
}

.sidebar-title {
	font-size: 32rpx;
	font-weight: bold;
}

.close-btn {
	font-size: 40rpx;
	color: #999;
	cursor: pointer;
	padding: 0 20rpx;
}

.history-list {
	height: calc(100% - 240rpx);
}

.history-item {
	padding: 30rpx;
	border-bottom: 1px solid #eee;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.history-item-content {
	flex: 1;
	margin-right: 20rpx;
}

.delete-btn {
	padding: 10rpx;
	opacity: 0.7;
	transition: opacity 0.3s;
}

.delete-btn:active {
	opacity: 1;
}

.question-text {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.time-text {
	font-size: 24rpx;
	color: #999;
}

.new-chat-btn {
	position: absolute;
	bottom: 0;
	width: 100%;
	padding: 30rpx 0;
	text-align: center;
	background-color: #f5f5f5;
	border-top: 1px solid #eee;
}

.circle-container {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
}

.circle-container .circle {
	width: 18rpx;
	height: 18rpx;
	border-radius: 50rpx;
	background-color: #777A8D;
	margin-right: 10rpx;
	animation: colorChange 1s linear infinite;
}

@keyframes colorChange {
	0% {
		background-color: #ffcc00;
	}
	66.67% {
		background-color: #ffcc00;
	}
	33.33% {
		background-color: #ffcc00;
	}
}

.circle-container .circle:nth-child(1) {
	animation-delay: 0s;
}

.circle-container .circle:nth-child(2) {
	animation-delay: 0.33s;
}

.circle-container .circle:nth-child(3) {
	animation-delay: 0.67s;
}
</style>